package io.springboot.jpa.examples.springbootjpaexamples.config.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;

/**
 * @author yzc
 * @description
 * @date 2018/9/25
 */
public class StatelessRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JsonWebToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String token = (String)principalCollection.getPrimaryPrincipal();
        String[] roles = JwtUtils.getRoles(token);
        String[] permissions = JwtUtils.getPermissions(token);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        if (roles != null) {
            simpleAuthorizationInfo.setRoles(new HashSet<>(Arrays.asList(roles)));
        }
        if (permissions != null) {
            simpleAuthorizationInfo.setStringPermissions(new HashSet<>(Arrays.asList(permissions)));
        }
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JsonWebToken token = (JsonWebToken) authenticationToken;
        if (!JwtUtils.verify(token.getToken())) {
            throw new AuthenticationException("无效的Token");
        }
        if (JwtUtils.isExpired(token.getToken())) {
            throw new AuthenticationException("Token已过期");
        }
        if (!StringUtils.hasLength(JwtUtils.getSubject(token.getToken()))) {
            throw new AuthenticationException("未识别的用户");
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), StatelessRealm.class.getName());
    }
}
